package com.xjl.springbootnetty.controller;

import com.xjl.springbootnetty.netty.init.ChatHandler;
import com.xjl.springbootnetty.utils.RedisUtil;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Iterator;

@RestController
public class TestController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisUtil redisUtil;




    @RequestMapping("/can")
    public String goid(@RequestParam(required = false) String value) {
        System.out.println("--------"+value);
        return value;
    }

    /**
     * @auther:
     * @date: 16:23 2018/8/29
     * @param: []
     * @return:
     * @Description: 执行redis写/读/生命周期
     */
    @RequestMapping(value = "/getRedis",method = RequestMethod.POST)
    @ResponseBody
    public String getRedis(){
        redisUtil.set("228782","sdfsd");
        redisTemplate.boundHashOps("namehash").put("a", "唐僧");
        redisTemplate.boundHashOps("namehash").put("b", "悟空");
        redisTemplate.boundHashOps("namehash").put("c", "八戒");
        redisTemplate.boundHashOps("namehash").put("d", "沙僧");
        return "res";
    }


    /**
     * @auther:
     * @date: 16:23 2018/8/29
     * @param: []
     * @return:
     * @Description: 添加netty主动推送
     */
    @RequestMapping(value = "/setChannelMessage",method = RequestMethod.POST)
    @ResponseBody
    public String setChannelMessage(String message){
        ChannelGroup users = ChatHandler.users;
        String channelId = (String)redisUtil.get(message);
        Iterator<Channel> iterator = users.stream().iterator();
        if(iterator.hasNext()){
            Channel next = iterator.next();
            System.out.println(next.id().asShortText());
            if(next.id().asShortText().equals(message)){
                next.writeAndFlush(new TextWebSocketFrame("[主动发消息：]"+message));
            }
        }
        return message+"res";
    }

}
